package com.mars.weixin.service.impl;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mars.base.common.utils.http.HttpHelper;
import com.mars.base.common.utils.http.HttpResult;
import com.mars.weixin.api.Api;
import com.mars.weixin.common.WeixinContext;
import com.mars.weixin.common.exception.WeixinException;
import com.mars.weixin.enums.MediaType;
import com.mars.weixin.service.ApiService;

@Service
public class ApiServiceImpl implements ApiService {

	private static Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);
	
	@Override
	public Object downloadMedia(String access_token, String mediaId, MediaType mediaType) {
		if(null != mediaId && !"".equals(mediaId.trim())) {
			if(null == access_token) {
				access_token = WeixinContext.getAccessToken() ;
			}
			String remoteFileUrl = Api.get(Api.MEDIA, access_token, mediaId) ;
			logger.debug("从微信服务器下载文件到本地，下载URL：{}", remoteFileUrl);
			
			if(MediaType.image == mediaType) {
				
			} else if(MediaType.voice == mediaType) {
				
			} else if(MediaType.video == mediaType) {
				
			} else if(MediaType.thumb == mediaType) {
				
			} else if(MediaType.voice == mediaType) {
				
			}
			
			try {
				HttpResult result = HttpHelper.executeDownloadFileWeiXin(remoteFileUrl) ;
				if(result.getStatus()) {
					logger.info("从微信服务器下载文件到本地，文件存放路径：{}", result.getFile().getAbsoluteFile());
				} else {
					logger.info("从微信服务器下载文件到本地发生错误：{}", result.getMessage());
				}
				return result ;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			throw WeixinException.MEDIAID_NOT_NULL ;
		}
		return null;
	}

	
	
}
